import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import DeviceList from '../views/DeviceList.vue'
import DeviceForm from '../views/DeviceForm.vue'
import DeviceConfig from '../views/DeviceConfig.vue'
import SubDeviceForm from '../views/SubDeviceForm.vue'
import DeviceKeyList from '../views/DeviceKeyList.vue'
import DeviceKeyForm from '../views/DeviceKeyForm.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/devices',
    name: 'DeviceList',
    component: DeviceList,
    meta: { requiresAuth: true }
  },
  {
    path: '/devices/add',
    name: 'AddDevice',
    component: DeviceForm,
    meta: { requiresAuth: true }
  },
  {
    path: '/devices/edit/:id',
    name: 'EditDevice',
    component: DeviceForm,
    meta: { requiresAuth: true }
  },
  {
    path: '/devices/config/:imei',
    name: 'DeviceConfig',
    component: DeviceConfig,
    meta: { requiresAuth: true }
  },
  {
    path: '/sub-devices/:mainImei/add',
    name: 'AddSubDevice',
    component: SubDeviceForm,
    meta: { requiresAuth: true }
  },
  {
    path: '/sub-devices/edit/:id',
    name: 'EditSubDevice',
    component: SubDeviceForm,
    meta: { requiresAuth: true }
  },
  {
    path: '/device-keys/:subDeviceId',
    name: 'DeviceKeyList',
    component: DeviceKeyList,
    meta: { requiresAuth: true }
  },
  {
    path: '/device-keys/:subDeviceId/add',
    name: 'AddDeviceKey',
    component: DeviceKeyForm,
    meta: { requiresAuth: true }
  },
  {
    path: '/device-keys/edit/:id',
    name: 'EditDeviceKey',
    component: DeviceKeyForm,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/devices')
  } else {
    next()
  }
})

export default router 